﻿using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace NetFrame.EnDecode
{
    public class SeProtobuf
    {
        public static byte[] Serialization<T>(T message) {
            if (message == null) { return null; }

            MemoryStream ms = new MemoryStream();

            try {
                Serializer.Serialize<T>(ms, message);
                byte[] result = new byte[ms.Length];
                //Buffer.BlockCopy(ms.ToArray(), 0, result, 0, result.Length);
                result = ms.ToArray();
                ms.Dispose();
                return result;
            }
            catch (Exception ex) {
                ms.Dispose();
                return null;
            }

        }

        public static T DeSerialization<T>(byte[] value) {
            if (value == null || value.Length == 0) { return default(T); }

            MemoryStream ms = new MemoryStream(value);

            T result;

            try {
                result = Serializer.Deserialize<T>(ms);
            }
            catch (Exception ex) {
                ms.Dispose();
                return default(T);
            }

            ms.Dispose();

            return result;

        }
    }
}
